package com.opal.utils;

import com.opal.consts.CommonConst;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.*;

import static org.thymeleaf.util.StringUtils.trim;

@Slf4j
public class CommonUtils {
	
	/**
	 * 返回当前日期
	 * @return 格式 2019-12-17
	 */
	public static String getCurrentDateString() {
		SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd");
		return sdf.format(new Date());
	}
	
	/**
	 * 返回当前日期时间
	 * @return 格式 2019-12-17 15:08:23
	 */
	public static String getCurrentDateTimeString() {
		SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		return sdf.format(new Date());
	}

	/**
	 * 根据组织获取相应的组织名称
	 * @param pkOrg
	 * @return
	 */
	public static String  getOrgName(String pkOrg){
		String orgName="";
		pkOrg=pkOrg==null?"":pkOrg;
		switch (pkOrg){
			case CommonConst.AOBAO:
				orgName=CommonConst.ORG_HUIZHOU_NAME;
				break;
			case CommonConst.ZHAOTING:
				orgName=CommonConst.ORG_ZHAOTING_NAME;
				break;
			case CommonConst.ORG_GUOJI_CODE:
				orgName=CommonConst.ORG_GUOJI_NAME;
				break;
			case CommonConst.ORG_XIANGGANG_CODE:
				orgName=CommonConst.ORG_XIANGGANG_NAME;
				break;
			default:
				orgName="";
		}
		return orgName;
	}
	
	
	/**
	 * 获取以时间(精确到毫秒)+随机的字符串值
	 * @return
	 */
    public static String getValue() {
    	StringBuilder sb= new StringBuilder();
    	Random r= new Random();
    	int i = r.nextInt(9000);
    	System.out.println("随机数是："+(i+1000));
    	String d = new SimpleDateFormat("yyyMMddhhmmssSSS").format(new Date());
    	sb.append(d);
    	sb.append(i+1000);
    	String string = sb.toString();
    	//补0
    	if(string.length()!=21) {
    		return string+"0";
    	}
    	return string;
    }

    public static  String getPropertiesResourcce(String key,String urlPath){
		Properties properties = new Properties();
		//InputStream resourceAsStream1 = Thread.currentThread().getContextClassLoader().getResourceAsStream("");
		InputStream resourceAsStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(urlPath);
		try {
			properties.load(resourceAsStream);
			return properties.getProperty(key);
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}finally {
			if (resourceAsStream != null) {
				try {
					resourceAsStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 是否是Ajax异步请求
	 *
	 * @param request
	 */
	public static boolean isAjaxRequest(HttpServletRequest request){
		String accept = request.getHeader("accept");
		if (accept != null && accept.indexOf("application/json") != -1){
			return true;
		}

		String xRequestedWith = request.getHeader("X-Requested-With");
		if (xRequestedWith != null && xRequestedWith.indexOf("XMLHttpRequest") != -1){
			return true;
		}

		String uri = request.getRequestURI();
		if (CommonUtils.inStringIgnoreCase(uri, ".json", ".xml")){
			return true;
		}

		String ajax = request.getParameter("__ajax");
		if (CommonUtils.inStringIgnoreCase(ajax, "json", "xml")){
			return true;
		}
		return false;
	}
	/**
	 * 是否包含字符串
	 *
	 * @param str 验证字符串
	 * @param strs 字符串组
	 * @return 包含返回true
	 */
	public static boolean inStringIgnoreCase(String str, String... strs){
		if (str != null && strs != null){
			for (String s : strs){
				if (str.equalsIgnoreCase(trim(s))){
					return true;
				}
			}
		}
		return false;
	}

    /**
     *      * Java实体类转Map
     *      * @param obj
     *      * @return
     *     
     */
    public static Map<String, Object> entityToMap(Object obj) {
        Map<String, Object> map = new HashMap<String, Object>();
        Class<?> clazz = obj.getClass();
        for (Field field : clazz.getDeclaredFields()) {
        	//设置有权限
            field.setAccessible(true);
            //获取成员变量名
            String fieldName = field.getName();
            Object object = null;
            try {
                object = field.get(obj);
            } catch (IllegalArgumentException | IllegalAccessException e) {
                log.info(e.getMessage());
            }
            map.put(fieldName, object);
        }
        return map;
    }


	/**
      * Map转实体类：要转换的Map的key跟实体类属性名相同的数据会转过去，不相同的字段会为null
      * @param clazz
      * @param map
      * @return
      */
	public static <T> T mapToEntity(Class<T> clazz, Map<String, Object> map) {
		T obj = null;
		try {
			BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
			obj = clazz.newInstance(); // 创建 JavaBean 对象
			PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
			// 给 JavaBean 对象的属性赋值
			for (int i = 0; i < propertyDescriptors.length; i++) {
				PropertyDescriptor descriptor = propertyDescriptors[i];
				String propertyName = descriptor.getName();
				if (map.containsKey(propertyName)) {
					Object value = map.get(propertyName);
					Object[] args = new Object[1];
					args[0] = value;
					try {
						descriptor.getWriteMethod().invoke(obj, args);
					} catch (InvocationTargetException e) {
						log.info(e.getMessage());
					}
				}
			}
		} catch (IllegalAccessException e) {
			log.info(e.getMessage());
		} catch (IntrospectionException e) {
			log.info(e.getMessage());
		} catch (IllegalArgumentException e) {
			log.info(e.getMessage());
		} catch (InstantiationException e) {
			log.info(e.getMessage());
		}
		return (T) obj;
	}

	/**
	 * 从字符串中提取数字
	 * @param str
	 * @return
	 */
	public static Long extractNum(String str) {
		str = str.trim();
		String str2 = "";
		if (str != null && !"".equals(str)) {
			for (int i = 0; i < str.length(); i++) {
				if (str.charAt(i) >= 48 && str.charAt(i) <= 57) {
					str2 += str.charAt(i);
				}
			}
		}
		return Long.parseLong(str2);
	}

}
